package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import com.caiyi.financial.nirvana.sms.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class FengHuoGateway extends BaseGateway {

    private static final Logger logger = LoggerFactory.getLogger(FengHuoGateway.class);

    private static final String FORMAT_DATE = "yyyyMMddHHmmss";

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = "";
        try {
            SimpleDateFormat format = new SimpleDateFormat(FORMAT_DATE);
            String seed = format.format(new Date());
            String password = MD5Util.encode((MD5Util.encode(info.getPassword()).toLowerCase() + seed)).toLowerCase();
            Map paramMap = new HashMap();
            paramMap.put("name", info.getAccount());
            paramMap.put("seed", seed);
            paramMap.put("key", password);
            paramMap.put("dest", entity.getPhone());
            paramMap.put("content", entity.getContent());
            paramMap.put("ext", entity.getAccessNumber());
            // paramMap.put("reference", entity.getMessageId());
            logger.info("FengHuoGateway send params：{},", paramMap);
            String response = doPost(info.getServerAddr(), paramMap);
            if (response == null) {
                result = "网关请求超时";
                return;
            }
            logger.info("FengHuoGateway send result：{},", response);
            String[] res = response.split(":");
            if (res[0].equalsIgnoreCase("success")) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
                result = res[1];
            } else {
                result = status + ":" + res[1];
            }
        } catch (Exception e) {
            logger.error("FengHuoGateway send error ! ", e);
        } finally {
            this.handlerResponse(entity, result, status);
        }
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        try {
            String param = entity.getParam();
            logger.info("FengHuoGateway notifyStatus param : {}", param);
            Map<String, String> paramMap = JSON.parseObject(param, Map.class);
            String reportList = paramMap.get("report");
            logger.info("FengHuoGateway notifyStatus report : {}", reportList);
            if (null != reportList && !"".equals(reportList)) {
                String[] reportArr = reportList.split(";");
                for (String report : reportArr) {
                    String[] paramArr = report.split(",");
                    int status = SmsMsgStatusEnum.SEND_FAIL.index;
                    String gatewayStatus = paramArr[2];
                    if (gatewayStatus.equals("DELIVRD")) {
                        status = SmsMsgStatusEnum.SEND_SUCCESS.index;
                    }
                    String messageId = JedisService.hget(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, paramArr[0] + paramArr[1]);
                    JedisService.hdel(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, paramArr[0] + paramArr[1]);
                    if (StringUtils.isBlank(messageId)) {
                        logger.warn("FengHuoGateway notifyStatus messageId is null params : {}", param);
                    }
                    receiveReport(status, messageId, gatewayStatus);
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("FengHuoGateway notifyStatus error ! ", e);
            return false;
        }
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        try {
            String param = entity.getParam();
            logger.info("FengHuoGateway receiveMsg param : {}", param);
            Map<String, String> paramMap = JSON.parseObject(param, Map.class);
            SmsReceiveMessage smsReceiveMessage = new SmsReceiveMessage();
            String accessNumber = paramMap.get("dest");
            String extend = accessNumber.substring(accessNumber.length() - 3);
            String account = JedisService.get(String.format(JedisKey.SMS_EXTEND_ACCOUNT, extend));
            String messageId = paramMap.get("reference");
            String phone = paramMap.get("src");
            String content = paramMap.get("content");
            smsReceiveMessage.setAccount(account);
            smsReceiveMessage.setAccessNumber(accessNumber);
            smsReceiveMessage.setCreateTime(new Date());
            smsReceiveMessage.setPhone(phone);
            smsReceiveMessage.setContent(content);
            smsReceiveMessage.setMessageId(messageId);
            receiveMessage(smsReceiveMessage);
            return true;
        } catch (Exception e) {
            logger.error("FengHuoGateway receiveMsg error ! ", e);
        }
        return false;
    }


    @Override
    public int queryBalance() {
        try {
            SimpleDateFormat format = new SimpleDateFormat(FORMAT_DATE);
            String seed = format.format(new Date());
            String password = MD5Util.encode((MD5Util.encode(info.getPassword()).toLowerCase() + seed)).toLowerCase();
            Map paramMap = new HashMap();
            paramMap.put("name", info.getAccount());
            paramMap.put("seed", seed);
            paramMap.put("key", password);
            logger.info("FengHuoGateway queryBalance param {}", paramMap);
            String response = HttpClientUtil.doPost(info.getServerAddr().replace("send", "balance"), paramMap);
            logger.info("{}余额查询结果:{}", info.getName(), response);
            String[] res = response.split(":");
            if (res[0].equalsIgnoreCase("success")) {
                return NumberUtils.toInt(res[1]);
            } else {
                logger.error("FengHuoGateway queryBalance response error : {}", res[0]);
            }
        } catch (Exception e) {
            logger.error("FengHuoGateway queryBalance error ! ", e);
        }
        return 0;
    }
}
